<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>在线考试系统</title>
  <link rel="stylesheet" href="../../static/css/all.min.css">
  <style>
    :root {
      --primary-color: #4361ee;
      --secondary-color: #3f37c9;
      --completed-color: #1a237e;
      --light-color: #f8f9fa;
      --dark-color: #212529;
      --border-radius: 8px;
      --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      --border-color: #e0e0e0;
    }

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background-color: #f5f7fa;
      color: var(--dark-color);
      line-height: 1.6;
      height: 100vh;
      overflow: hidden;
    }

    .container {
      display: flex;
      max-width: 1200px;
      height: 100%;
      margin: 0 auto;
      background: white;
      border-radius: var(--border-radius);
      box-shadow: var(--box-shadow);
      overflow: hidden;
    }

    /* 左侧导航栏 */
    .sidebar {
      width: 250px;
      background-color: #f8f9fa;
      border-right: 1px solid var(--border-color);
      padding: 20px;
      overflow-y: auto;
    }

    .sidebar-header {
      padding-bottom: 15px;
      border-bottom: 1px solid var(--border-color);
      margin-bottom: 15px;
    }

    .sidebar-title {
      font-size: 18px;
      font-weight: 600;
      color: var(--dark-color);
    }

    .question-nav {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }

    .question-category {
      margin-bottom: 10px;
    }

    .category-title {
      padding: 8px 0;
      font-weight: 500;
      color: var(--primary-color);
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .question-list {
      list-style: none;
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }

    .question-item {
      width: 36px;
      height: 36px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.2s;
      border-radius: var(--border-radius);
      background-color: white;
      border: 1px solid var(--border-color);
    }

    .question-item:hover {
      border-color: var(--primary-color);
    }

    .question-item.completed {
      background-color: var(--primary-color);
      color: white;
      border-color: var(--primary-color);
    }

    .question-item.current {
      border: 2px solid var(--primary-color);
      background-color: white;
      color: var(--dark-color);
      font-weight: bold;
    }

    /* 右侧内容区 */
    .main-content {
      flex: 1;
      padding: 30px;
      overflow-y: auto;
      height: 100%;
    }

    .paper-header {
      margin-bottom: 30px;
      text-align: center;
    }

    .paper-title {
      font-size: 24px;
      font-weight: 600;
      margin-bottom: 10px;
    }

    .paper-info {
      color: #6c757d;
      font-size: 14px;
      display: flex;
      justify-content: center;
      gap: 20px;
    }

    /* 计时器样式 - 固定在右上角 */
    .timer {
      position: fixed;
      top: 20px;
      right: 100px;
      background-color: white;
      padding: 8px 12px;
      border-radius: var(--border-radius);
      box-shadow: var(--box-shadow);
      z-index: 999;
      font-size: 16px;
      color: #dc3545;
      font-weight: 600;
    }

    .question-container {
      margin-bottom: 40px;
    }

    .question-type {
      font-size: 18px;
      font-weight: 500;
      color: var(--primary-color);
      margin-bottom: 15px;
      padding-bottom: 8px;
      border-bottom: 1px solid var(--border-color);
    }

    .question-block {
      background-color: #f8f9fa;
      border-radius: var(--border-radius);
      padding: 20px;
      margin-bottom: 20px;
      scroll-margin-top: 80px;
      transition: all 0.3s;
    }

    .question-title {
      font-weight: 500;
      margin-bottom: 15px;
      display: flex;
    }

    .question-text {
      margin-bottom: 15px;
    }

    .options-list {
      list-style: none;
    }

    .option-item {
      margin-bottom: 10px;
      display: flex;
      align-items: flex-start;
      cursor: pointer;
      padding: 8px 12px;
      border-radius: 4px;
    }

    .option-item:hover {
      background-color: rgba(67, 97, 238, 0.05);
    }

    .option-radio {
      display: none;
    }

    .option-label {
      width: 24px;
      height: 24px;
      border: 1px solid #adb5bd;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 10px;
      flex-shrink: 0;
    }

    .option-radio:checked + .option-label {
      background-color: var(--primary-color);
      border-color: var(--primary-color);
      color: white;
    }

    .option-radio:checked + .option-label::after {
      content: "✓";
      font-size: 12px;
    }

    .answer-input {
      width: 100%;
      padding: 10px 12px;
      border: 1px solid var(--border-color);
      border-radius: var(--border-radius);
      font-family: inherit;
    }

    .answer-input:focus {
      outline: none;
      border-color: var(--primary-color);
    }

    .answer-textarea {
      width: 100%;
      min-height: 120px;
      padding: 12px;
      border: 1px solid var(--border-color);
      border-radius: var(--border-radius);
      font-family: inherit;
      resize: vertical;
    }

    .answer-textarea:focus {
      outline: none;
      border-color: var(--primary-color);
    }

    /* 操作按钮 */
    .action-buttons {
      display: flex;
      justify-content: flex-end;
      margin-top: 30px;
      padding-top: 20px;
      border-top: 1px solid var(--border-color);
    }

    .btn {
      padding: 10px 20px;
      border: none;
      border-radius: var(--border-radius);
      cursor: pointer;
      font-size: 14px;
      transition: all 0.3s;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .btn:disabled {
      background-color: #ccc;
      cursor: not-allowed;
      opacity: 0.7;
    }

    .btn-primary {
      background-color: var(--primary-color);
      color: white;
    }

    .btn-primary:hover:not(:disabled) {
      background-color: var(--secondary-color);
    }

    .btn-outline {
      background-color: transparent;
      border: 1px solid var(--border-color);
      color: var(--dark-color);
      margin-right: 10px;
    }

    /* 加载提示 */
    .loading {
      text-align: center;
      padding: 40px;
      color: #6c757d;
    }

    .loading i {
      font-size: 24px;
      margin-bottom: 10px;
      animation: spin 1.5s linear infinite;
    }

    @keyframes spin {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }

    /* 提交加载遮罩层 */
    #loadingMask {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.3);
      z-index: 9999;
      justify-content: center;
      align-items: center;
      flex-direction: column;
    }

    #loadingMask i {
      font-size: 40px;
      color: white;
      animation: spin 1.5s linear infinite;
    }

    #loadingMask p {
      color: white;
      margin-top: 10px;
      font-size: 16px;
    }



  </style>
</head>
<body>
<div class="container">
  <!-- 左侧导航栏 -->
  <div class="sidebar">
    <div class="sidebar-header">
      <div class="sidebar-title">试卷导航</div>
    </div>
    <div class="question-nav">
      <!-- 选择题 -->
      <div class="question-category navi-select-question">
        <div class="category-title">
          <span>选择题</span>
          <span>0题</span>
        </div>
        <ul class="question-list select-question-list"></ul>
      </div>

      <!-- 填空题 -->
      <div class="question-category navi-fill-question">
        <div class="category-title">
          <span>填空题</span>
          <span>0题</span>
        </div>
        <ul class="question-list fill-question-list"></ul>
      </div>

      <!-- 判断题 -->
      <div class="question-category navi-judge-question">
        <div class="category-title">
          <span>判断题</span>
          <span>0题</span>
        </div>
        <ul class="question-list judge-question-list"></ul>
      </div>

      <!-- 简答题 -->
      <div class="question-category navi-short-question">
        <div class="category-title">
          <span>简答题</span>
          <span>0题</span>
        </div>
        <ul class="question-list short-question-list"></ul>
      </div>

      <!-- 计算题 -->
      <div class="question-category navi-calculate-question">
        <div class="category-title">
          <span>计算题</span>
          <span>0题</span>
        </div>
        <ul class="question-list calculate-question-list"></ul>
      </div>
    </div>
  </div>

  <!-- 右侧内容区 -->
  <div class="main-content">
    <div class="paper-header">
      <h1 class="paper-title">加载中...</h1>
      <!-- 固定计时器 -->
      <div class="timer" id="examTimer">
        <span>剩余时间：</span>
        <span id="timerDisplay" style="color: #dc3545; font-weight: bold;">--:--</span>
      </div>
      <div class="paper-info">
        <span class="duration">时间：加载中...</span>
        <span class="total-score">总分：0分</span>
      </div>
    </div>

    <!-- 选择题 -->
    <div class="question-container">
      <h3 class="question-type first-level-title-choice-questions">
        <i class="fas fa-check-circle"></i> 一、选择题
      </h3>
      <div class="select-question loading">
        <i class="fas fa-spinner"></i>
        <div>加载选择题中...</div>
      </div>
    </div>

    <!-- 填空题 -->
    <div class="question-container">
      <h3 class="question-type first-level-title-fill-questions">
        <i class="fas fa-pencil-alt"></i> 二、填空题
      </h3>
      <div class="fill-question loading">
        <i class="fas fa-spinner"></i>
        <div>加载填空题中...</div>
      </div>
    </div>

    <!-- 判断题 -->
    <div class="question-container">
      <h3 class="question-type first-level-title-judge-questions">
        <i class="fas fa-balance-scale"></i> 三、判断题
      </h3>
      <div class="judge-question loading">
        <i class="fas fa-spinner"></i>
        <div>加载判断题中...</div>
      </div>
    </div>

    <!-- 简答题 -->
    <div class="question-container">
      <h3 class="question-type first-level-title-short-questions">
        <i class="fas fa-comment-dots"></i> 四、简答题
      </h3>
      <div class="short-question loading">
        <i class="fas fa-spinner"></i>
        <div>加载简答题中...</div>
      </div>
    </div>

    <!-- 计算题 -->
    <div class="question-container">
      <h3 class="question-type first-level-title-calculate-questions">
        <i class="fas fa-calculator"></i> 五、计算题
      </h3>
      <div class="calculate-question loading">
        <i class="fas fa-spinner"></i>
        <div>加载计算题中...</div>
      </div>
    </div>

    <div class="action-buttons">
      <button class="btn btn-primary" id="submit-btn">
        <i class="fas fa-paper-plane"></i> 提交试卷
      </button>
    </div>
  </div>
</div>

<!-- 全局加载遮罩层 -->
<div id="loadingMask">
  <i class="fas fa-spinner fa-spin"></i>
  <p>正在提交试卷，请稍候...</p>
</div>

<!-- 引入外部JS -->
<script src="../../static/js/jquery-3.6.0.min.js"></script>
<script src="../../static/js/jquery.cookie.min.js"></script>
<script>
  // 全局变量定义
  const examId = $.cookie("examId") || "1";
  const student = $.cookie("studentName")
  let totalScore = 0;
  let multipleChoiceCount = 0;
  let fillInTheBlankCount = 0;
  let trueOrFalseCount = 0;
  let shortAnswerCount = 0;
  let calculationCount = 0;
  let examTime = $.cookie("examtime")
  // 倒计时相关变量
  let examDurationMin = 0; // 考试总时长（分钟）
  let totalSeconds = 0;    // 总秒数
  let remainingSeconds = 0; // 剩余秒数
  let timerInterval = null; // 定时器

  // 页面加载完成后初始化
  document.addEventListener('DOMContentLoaded', function() {
    // 按顺序加载所有题目，确保DOM生成后再绑定事件
    loadAllQuestions().then(() => {
      initQuestionNavigation();
    }).catch(error => {
      console.error("初始化失败:", error);
      alert("加载试卷失败，请刷新页面重试");
    });
  });

  // 统一加载所有题目
  function loadAllQuestions() {
    return new Promise((resolve) => {
      loadExamInfo(() => {
        LoadMultipleChoiceQuestions(() => {
          LoadFillInTheBlankQuestions(() => {
            LoadingTrueOrFalseQuestions(() => {
              LoadShortAnswerQuestions(() => {
                LoadingCalculationQuestions(() => {
                  resolve();
                });
              });
            });
          });
        });
      });
    });
  }

  // 初始化导航联动功能
  function initQuestionNavigation() {
    const questionItems = document.querySelectorAll('.question-item');
    const questionBlocks = document.querySelectorAll('.question-block');
    let currentQuestion = questionItems.length > 0 ? questionItems[0].getAttribute('data-id') : 'q1';

    // 更新导航状态
    function updateNavStatus() {
      questionItems.forEach(item => {
        const questionId = item.getAttribute('data-id');
        item.classList.remove('current', 'completed');

        if (questionId === currentQuestion) {
          item.classList.add('current');
        } else if (isQuestionCompleted(questionId)) {
          item.classList.add('completed');
        }
      });
    }

    // 检查题目是否已完成
    function isQuestionCompleted(questionId) {
      const block = document.getElementById(questionId);
      if (!block) return false;

      // 选择题/判断题
      const radio = block.querySelector('input[type="radio"]:checked');
      if (radio) return true;

      // 填空题
      const input = block.querySelector('.answer-input');
      if (input && input.value.trim()) return true;

      // 简答题/计算题
      const textarea = block.querySelector('.answer-textarea');
      if (textarea && textarea.value.trim()) return true;

      return false;
    }

    // 点击导航项滚动到对应题目
    questionItems.forEach(item => {
      item.addEventListener('click', function() {
        const questionId = this.getAttribute('data-id');
        currentQuestion = questionId;

        const targetBlock = document.getElementById(questionId);
        if (targetBlock) {
          targetBlock.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
          });
        }
        updateNavStatus();
      });
    });

    // 滚动时更新当前题目
    const mainContent = document.querySelector('.main-content');
    mainContent.addEventListener('scroll', function() {
      const scrollTop = mainContent.scrollTop;

      // 遍历所有题目块，找到当前可见的题目
      questionBlocks.forEach(block => {
        const rect = block.getBoundingClientRect();
        // 题目顶部进入可视区域（距离顶部100px内）
        if (rect.top >= 0 && rect.top <= 100) {
          const questionId = block.id;
          if (questionId !== currentQuestion) {
            currentQuestion = questionId;
            updateNavStatus();
          }
        }
      });
    });

    // 监听输入变化，更新完成状态
    document.querySelectorAll('input, textarea').forEach(input => {
      input.addEventListener('change', updateNavStatus);
      input.addEventListener('input', updateNavStatus);
    });

    // 初始化导航状态
    updateNavStatus();

    // 绑定按钮事件
    bindSubmitEvent();
  }

  // 绑定提交按钮事件
  function bindSubmitEvent() {
    $("#submit-btn").click(function() {
      if (confirm("确定要提交试卷吗？提交后无法修改！")) {
        const answers = collectAnswers();
        submitToAI(answers);
      }
    });
  }

  // 收集答案
  function collectAnswers() {
    const answers = [];
    const questionItems = document.querySelectorAll('.question-item');

    questionItems.forEach(item => {
      const qId = item.getAttribute('data-id');
      const questionBlock = document.getElementById(qId);
      if (!questionBlock) return;

      // 获取题型
      const type = item.closest(".question-category")
              .querySelector(".category-title span:first-child")
              .textContent;
      // 获取题目内容
      let questionText = questionBlock.querySelector(".question-title span:first-child").textContent;
      questionText = questionText.replace(/\(\d+分\)/, "").trim();

      // 获取选项（仅选择题）
      let options = [];
      if (type === "选择题") {
        options = Array.from(questionBlock.querySelectorAll(".option-item")).map(optItem => {
          const letter = optItem.querySelector(".option-label").textContent;
          const text = optItem.querySelector(".option-text").textContent;
          return `${letter}. ${text}`;
        });
      }

      // 获取用户答案
      let userAnswer = "";
      // 选择题和判断题
      const selectedRadio = questionBlock.querySelector('input[type="radio"]:checked');
      if (selectedRadio) {
        userAnswer = selectedRadio.value;
      }
      // 填空题
      const textInput = questionBlock.querySelector('.answer-input');
      if (textInput) {
        userAnswer = textInput.value.trim();
      }
      // 简答题和计算题
      const textarea = questionBlock.querySelector('.answer-textarea');
      if (textarea) {
        userAnswer = textarea.value.trim();
      }

      answers.push({
        question_id: qId,
        type: type,
        question: questionText,
        options: options,
        user_answer: userAnswer
      });
    });

    return answers;
  }

  // 提交到AI判题
  function submitToAI(answers) {
    const requestData = {
      student: student,
      exam_id: examId,
      questions: answers
    };
    console.log("提交给ai的内容：" + JSON.stringify(requestData, null, 2))

    // 显示加载遮罩层并禁用提交按钮
    $("#loadingMask").css("display", "flex");
    $("#submit-btn").prop("disabled", true);

    $.ajax({
      url: "/ExamDetail/SubmitToAI",
      type: "post",
      dataType: "json",
      contentType: "application/json",
      data: JSON.stringify(requestData),
      success: function(res) {
        console.log(student)
        console.log(res)

        // 隐藏加载遮罩层并启用提交按钮
        $("#loadingMask").hide();
        $("#submit-btn").prop("disabled", false);

        if (res.code === 200) {
          // alert(`提交成功！您的得分是：${res.data}分`);
          location.href = "MyExam";
        } else {
          alert("提交失败：" + (res.msg || "未知错误"));
        }
      },
      error: function() {
        // 隐藏加载遮罩层并启用提交按钮
        $("#loadingMask").hide();
        $("#submit-btn").prop("disabled", false);
        alert("提交请求失败，请重试");
      }
    });
  }

  // 加载试卷基本信息
  function loadExamInfo(callback) {
    $.ajax({
      url: "/ExamDetail/LoadExamInfo",
      type: "post",
      dataType: "json",
      data: { id: examId },
      success: function(res) {
        if (res && res.data) {
          $(".paper-title").text(res.data.name || "未命名试卷");
          // 获取考试时长，假设接口返回的 duration 是分钟数
          examDurationMin = res.data.duration || 120; // 默认120分钟
          totalSeconds = examDurationMin * 60;
          remainingSeconds = totalSeconds;

          if (res.data.duration === 0) {
            $(".duration").text("时间：不限时");
          } else {
            $(".duration").text("时间：" + res.data.duration + "分钟");
          }
          // 启动倒计时
          startTimer();
        }
        if (callback) callback();
      },
      error: function() {
        alert("获取考试信息失败，请联系管理员");
        // 若获取失败，设置默认时长启动倒计时
        examDurationMin = 120;
        totalSeconds = examDurationMin * 60;
        remainingSeconds = totalSeconds;
        startTimer();
        if (callback) callback();
      }
    });
  }

  // 启动倒计时
  function startTimer() {
    const timerDisplay = document.getElementById('timerDisplay');
    if (!timerDisplay) {
      console.error('未找到计时器显示元素');
      return;
    }
    // 先清除可能存在的旧定时器
    if (timerInterval) {
      clearInterval(timerInterval);
    }
    // 每秒更新一次
    timerInterval = setInterval(() => {
      remainingSeconds--;
      $(".btn-primary").on("click",function(){
        clearInterval(timerInterval);
      })
      // 倒计时结束逻辑
      if (remainingSeconds < 0) {
        clearInterval(timerInterval);
        timerDisplay.innerText = "00:00";
        alert("考试时间已结束！将自动提交试卷");
        // 自动提交试卷
        const answers = collectAnswers();
        submitToAI(answers);
        return;
      }
      // 更新显示
      updateTimerDisplay(timerDisplay);
    }, 1000);
    // 初始化显示
    updateTimerDisplay(timerDisplay);
  }

  // 更新计时器显示
  function updateTimerDisplay(displayEle) {
    const minutes = Math.floor(remainingSeconds / 60);
    const seconds = remainingSeconds % 60;
    // 格式化显示为两位数字
    const displayText = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
    displayEle.innerText = displayText;
    // 时间不足5分钟时变红提醒
    if (remainingSeconds < 300) {
      displayEle.style.color = '#ff0000';
    } else {
      displayEle.style.color = '#dc3545';
    }
  }

  // 加载选择题
  function LoadMultipleChoiceQuestions(callback) {
    $.ajax({
      url: "/ExamDetail/LoadMultipleChoiceQuestions",
      type: "post",
      dataType: "json",
      data: { e_id: examId },
      success: function(res) {
        let arr = res && res.data ? res.data : [];
        multipleChoiceCount = arr.length;

        // 清空旧内容
        $(".select-question").empty().removeClass('loading');
        $(".first-level-title-choice-questions").empty();

        // 渲染题型标题
        const totalChoiceScore = arr.reduce((sum, item) => sum + (parseInt(item.score) || 0), 0);
        totalScore += totalChoiceScore;
        $(".first-level-title-choice-questions").append(`
                            <i class="fas fa-check-circle"></i> 一、选择题（共${multipleChoiceCount}题，共${totalChoiceScore}分）
                        `);
        $(".total-score").text("总分：" + totalScore + "分");

        // 更新左侧导航标题
        $(".navi-select-question .category-title span:last").text(`${multipleChoiceCount}题`);

        // 渲染右侧题目内容
        arr.forEach((item, index) => {
          const options = JSON.parse(item.option || "[]");
          const qIndex = index + 1;
          const qId = `q${qIndex}`;
          $(".select-question").append(`
                                <div class="question-block" id="${qId}">
                                    <div class="question-title">
                                        <span>${qIndex}. ${item.content || '无题目内容'}</span>
                                        <span style="margin-left: auto; color: #6c757d; font-size: 14px;">(${item.score || 0}分)</span>
                                    </div>
                                    <ul class="options-list">
                                        ${options.map((opt, optIndex) => {
            const optLetter = String.fromCharCode(65 + optIndex); // A, B, C, D...
            return `
                                                <li class="option-item">
                                                    <input type="radio" name="${qId}" id="${qId}-${optLetter}" class="option-radio" value="${optLetter}">
                                                    <label for="${qId}-${optLetter}" class="option-label">${optLetter}</label>
                                                    <div class="option-text">${opt || ''}</div>
                                                </li>
                                            `;
          }).join('')}
                                    </ul>
                                </div>
                            `);
        });

        // 渲染左侧导航
        const selectQuestionList = $(".select-question-list");
        selectQuestionList.empty();
        for (let i = 1; i <= multipleChoiceCount; i++) {
          const qId = `q${i}`;
          selectQuestionList.append(`
                                <li class="question-item select-question-num ${i === 1 ? 'current' : ''}" data-id="${qId}">${i}</li>
                            `);
        }

        if (callback) callback();
      },
      error: function() {
        alert("获取选择题信息失败，请联系管理员");
        $(".select-question").empty().text("加载选择题失败");
        if (callback) callback();
      }
    });
  }

  // 加载填空题
  function LoadFillInTheBlankQuestions(callback) {
    $.ajax({
      url: "/ExamDetail/LoadFillInTheBlankQuestions",
      type: "post",
      dataType: "json",
      data: { e_id: examId },
      success: function(res) {
        let arr = res && res.data ? res.data : [];
        fillInTheBlankCount = arr.length;

        // 计算起始题号（选择题之后）
        const startIndex = multipleChoiceCount + 1;

        // 清空旧内容
        $(".fill-question").empty().removeClass('loading');
        $(".first-level-title-fill-questions").empty();

        // 渲染题型标题
        const totalFillScore = arr.reduce((sum, item) => sum + (parseInt(item.score) || 0), 0);
        totalScore += totalFillScore;
        $(".first-level-title-fill-questions").append(`
                            <i class="fas fa-pencil-alt"></i> 二、填空题（共${fillInTheBlankCount}题，共${totalFillScore}分）
                        `);
        $(".total-score").text("总分：" + totalScore + "分");

        // 更新左侧导航标题
        $(".navi-fill-question .category-title span:last").text(`${fillInTheBlankCount}题`);

        // 渲染右侧题目内容
        arr.forEach((item, index) => {
          const qIndex = startIndex + index;
          const qId = `q${qIndex}`;
          $(".fill-question").append(`
                                <div class="question-block" id="${qId}">
                                    <div class="question-title">
                                        <span>${qIndex}. ${item.content || '无题目内容'}</span>
                                        <span style="margin-left: auto; color: #6c757d; font-size: 14px;">(${item.score || 0}分)</span>
                                    </div>
                                    <input type="text" class="answer-input" placeholder="请在此输入答案">
                                </div>
                            `);
        });

        // 渲染左侧导航
        const fillQuestionList = $(".fill-question-list");
        fillQuestionList.empty();
        for (let i = 0; i < fillInTheBlankCount; i++) {
          const qIndex = startIndex + i;
          const qId = `q${qIndex}`;
          fillQuestionList.append(`
                                <li class="question-item fill-question-num" data-id="${qId}">${qIndex}</li>
                            `);
        }

        if (callback) callback();
      },
      error: function() {
        alert("获取填空题信息失败，请联系管理员");
        $(".fill-question").empty().text("加载填空题失败");
        if (callback) callback();
      }
    });
  }

  // 加载判断题
  function LoadingTrueOrFalseQuestions(callback) {
    $.ajax({
      url: "/ExamDetail/LoadingTrueOrFalseQuestions",
      type: "post",
      dataType: "json",
      data: { e_id: examId },
      success: function(res) {
        let arr = res && res.data ? res.data : [];
        trueOrFalseCount = arr.length;

        // 计算起始题号（选择题+填空题之后）
        const startIndex = multipleChoiceCount + fillInTheBlankCount + 1;

        // 清空旧内容
        $(".judge-question").empty().removeClass('loading');
        $(".first-level-title-judge-questions").empty();

        // 渲染题型标题
        const totalJudgeScore = arr.reduce((sum, item) => sum + (parseInt(item.score) || 0), 0);
        totalScore += totalJudgeScore;
        $(".first-level-title-judge-questions").append(`
                            <i class="fas fa-balance-scale"></i> 三、判断题（共${trueOrFalseCount}题，共${totalJudgeScore}分）
                        `);
        $(".total-score").text("总分：" + totalScore + "分");

        // 更新左侧导航标题
        $(".navi-judge-question .category-title span:last").text(`${trueOrFalseCount}题`);

        // 渲染右侧题目内容
        arr.forEach((item, index) => {
          const qIndex = startIndex + index;
          const qId = `q${qIndex}`;
          $(".judge-question").append(`
                                <div class="question-block" id="${qId}">
                                    <div class="question-title">
                                        <span>${qIndex}. ${item.content || '无题目内容'}</span>
                                        <span style="margin-left: auto; color: #6c757d; font-size: 14px;">(${item.score || 0}分)</span>
                                    </div>
                                    <div style="display: flex; gap: 15px; margin-top: 10px;">
                                        <label style="display: flex; align-items: center; cursor: pointer;">
                                            <input type="radio" name="${qId}" value="正确" style="margin-right: 5px;"> 正确
                                        </label>
                                        <label style="display: flex; align-items: center; cursor: pointer;">
                                            <input type="radio" name="${qId}" value="错误" style="margin-right: 5px;"> 错误
                                        </label>
                                    </div>
                                </div>
                            `);
        });

        // 渲染左侧导航
        const judgeQuestionList = $(".judge-question-list");
        judgeQuestionList.empty();
        for (let i = 0; i < trueOrFalseCount; i++) {
          const qIndex = startIndex + i;
          const qId = `q${qIndex}`;
          judgeQuestionList.append(`
                                <li class="question-item judge-question-num" data-id="${qId}">${qIndex}</li>
                            `);
        }

        if (callback) callback();
      },
      error: function() {
        alert("获取判断题信息失败，请联系管理员");
        $(".judge-question").empty().text("加载判断题失败");
        if (callback) callback();
      }
    });
  }

  // 加载简答题
  function LoadShortAnswerQuestions(callback) {
    $.ajax({
      url: "/ExamDetail/LoadShortAnswerQuestions",
      type: "post",
      dataType: "json",
      data: { e_id: examId },
      success: function(res) {
        console.log(res)
        let arr = res && res.data ? res.data : [];
        shortAnswerCount = arr.length;
        console.log(arr)
        // 计算起始题号（选择+填空+判断之后）
        const startIndex = multipleChoiceCount + fillInTheBlankCount + trueOrFalseCount + 1;

        // 清空旧内容
        $(".short-question").empty().removeClass('loading');
        $(".first-level-title-short-questions").empty();

        // 渲染题型标题
        const totalShortScore = arr.reduce((sum, item) => sum + (parseInt(item.score) || 0), 0);
        totalScore += totalShortScore;
        $(".first-level-title-short-questions").append(`
                            <i class="fas fa-comment-dots"></i> 四、简答题（共${shortAnswerCount}题，共${totalShortScore}分）
                        `);
        $(".total-score").text("总分：" + totalScore + "分");

        // 更新左侧导航标题
        $(".navi-short-question .category-title span:last").text(`${shortAnswerCount}题`);

        // 渲染右侧题目内容
        arr.forEach((item, index) => {
          const qIndex = startIndex + index;
          const qId = `q${qIndex}`;
          $(".short-question").append(`
                                <div class="question-block" id="${qId}">
                                    <div class="question-title">
                                        <span>${qIndex}. ${item.content || '无题目内容'}</span>
                                        <span style="margin-left: auto; color: #6c757d; font-size: 14px;">(${item.score || 0}分)</span>
                                    </div>
                                    <textarea class="answer-textarea" placeholder="请在此输入答案"></textarea>
                                </div>
                            `);
        });

        // 渲染左侧导航
        const shortQuestionList = $(".short-question-list");
        shortQuestionList.empty();
        for (let i = 0; i < shortAnswerCount; i++) {
          const qIndex = startIndex + i;
          const qId = `q${qIndex}`;
          shortQuestionList.append(`
                                <li class="question-item short-question-num" data-id="${qId}">${qIndex}</li>
                            `);
        }

        if(callback) callback();
      },
      error: function() {
        alert("获取简答题信息失败，请联系管理员");
        $(".short-question").empty().text("加载简答题失败");
        if (callback) callback();
      }
    });
  }

  // 加载计算题
  function LoadingCalculationQuestions(callback) {
    $.ajax({
      url: "/ExamDetail/LoadingCalculationQuestions",
      type: "post",
      dataType: "json",
      data: { e_id: examId },
      success: function(res) {
        let arr = res && res.data ? res.data : [];
        calculationCount = arr.length;

        // 计算起始题号（前面所有题型之后）
        const startIndex = multipleChoiceCount + fillInTheBlankCount + trueOrFalseCount + shortAnswerCount + 1;

        // 清空旧内容
        $(".calculate-question").empty().removeClass('loading');
        $(".first-level-title-calculate-questions").empty();

        // 渲染题型标题
        const totalCalculateScore = arr.reduce((sum, item) => sum + (parseInt(item.score) || 0), 0);
        totalScore += totalCalculateScore;
        $(".first-level-title-calculate-questions").append(`
                            <i class="fas fa-calculator"></i> 五、计算题（共${calculationCount}题，共${totalCalculateScore}分）
                        `);
        $(".total-score").text("总分：" + totalScore + "分");

        // 更新左侧导航标题
        $(".navi-calculate-question .category-title span:last").text(`${calculationCount}题`);

        // 渲染右侧题目内容
        arr.forEach((item, index) => {
          const qIndex = startIndex + index;
          const qId = `q${qIndex}`;
          $(".calculate-question").append(`
                                <div class="question-block" id="${qId}">
                                    <div class="question-title">
                                        <span>${qIndex}. ${item.content || '无题目内容'}</span>
                                        <span style="margin-left: auto; color: #6c757d; font-size: 14px;">(${item.score || 0}分)</span>
                                    </div>
                                    <div class="question-text">${item.text || ''}</div>
                                    <textarea class="answer-textarea" placeholder="请在此输入解题过程"></textarea>
                                </div>
                            `);
        });

        // 渲染左侧导航
        const calculateQuestionList = $(".calculate-question-list");
        calculateQuestionList.empty();
        for (let i = 0; i < calculationCount; i++) {
          const qIndex = startIndex + i;
          const qId = `q${qIndex}`;
          calculateQuestionList.append(`
                                <li class="question-item calculate-question-num" data-id="${qId}">${qIndex}</li>
                            `);
        }

        if (callback) callback();
      },
      error: function() {
        alert("获取计算题信息失败，请联系管理员");
        $(".calculate-question").empty().text("加载计算题失败");
        if (callback) callback();
      }
    });
  }

  // 页面关闭时清除定时器
  window.addEventListener('beforeunload', function() {
    if (timerInterval) {
      clearInterval(timerInterval);
    }
  });
</script>
</body>
</html>
